package com.maochd.cloud.excel.convert;

import cn.hutool.core.date.DatePattern;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.apache.poi.ss.usermodel.DateUtil;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class TimeStampConvert implements Converter<Long> {

    private final static DateTimeFormatter DTF = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);

    @Override
    public Class<?> supportJavaTypeKey() {
        return Converter.super.supportJavaTypeKey();
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return Converter.super.supportExcelTypeKey();
    }

    @Override
    public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        LocalDateTime localDateTime = contentProperty != null && contentProperty.getDateTimeFormatProperty() != null ?
                DateUtil.getLocalDateTime(cellData.getNumberValue().doubleValue(), contentProperty.getDateTimeFormatProperty().getUse1904windowing())
                : DateUtil.getLocalDateTime(cellData.getNumberValue().doubleValue(), globalConfiguration.getUse1904windowing());
        return localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

    @Override
    public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (value == -1) {
            return new WriteCellData<>("-");
        }
        LocalDateTime localDateTime = Instant.ofEpochMilli(value).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
        return new WriteCellData<>(localDateTime.format(DTF));
    }
}
